package com.zahb.qadx.ui.activity;

import android.content.Intent;
import android.util.Pair;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.widget.AppCompatImageView;
import androidx.appcompat.widget.AppCompatTextView;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import androidx.viewpager2.widget.ViewPager2;

import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;
import com.zahb.qadx.R;
import com.zahb.qadx.base.BaseActivity;
import com.zahb.qadx.base.BaseApplication;
import com.zahb.qadx.model.CommonResponse;
import com.zahb.qadx.model.NoteBean;
import com.zahb.qadx.model.TrainAllBean;
import com.zahb.qadx.net.RetrofitService;
import com.zahb.qadx.ui.fragment.HandoutFragment;
import com.zahb.qadx.ui.fragment.OfflineTrainFragment;
import com.zahb.qadx.ui.fragment.TrainTaskListFragment;
import com.zahb.qadx.util.Constant;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;

public class TrainDetailsActivity extends BaseActivity {

    @BindView(R.id.tv_train_classname)
    AppCompatTextView train_classname;
    @BindView(R.id.tv_train_introduction)
    AppCompatTextView train_introduction;
    @BindView(R.id.tv_train_time)
    AppCompatTextView train_time;

    @BindView(R.id.tv_train_status)
    AppCompatTextView train_status;
    @BindView(R.id.tab_layout_train)
    TabLayout mTabLayout;
    @BindView(R.id.view_pager2_train)
    ViewPager2 mViewPager2;
    @BindView(R.id.iv_head)
    AppCompatImageView ivHead;
    @BindView(R.id.ivCard)
    ImageView ivCard;
    @BindView(R.id.tvCard)
    TextView tvCard;

    private List<String> mTitles = new ArrayList<>();
    private List<Fragment> fragmentList = new ArrayList<>();

    private int classId;

    OfflineTrainFragment offlineTrainFragment = new OfflineTrainFragment();
    HandoutFragment handoutFragment = new HandoutFragment();
    TrainTaskListFragment trainTaskListFragment = new TrainTaskListFragment();

    @Override
    protected int getLayout() {
        return R.layout.activity_train_details;
    }

    @Override
    protected void initViews() {
        mUnbinder = ButterKnife.bind(this);
        classId = getIntent().getIntExtra("id", 0);


        offlineTrainFragment.setArguments(getIntent().getExtras());
        Objects.requireNonNull(getIntent().getExtras()).putInt("data", 0);
        handoutFragment.setArguments(getIntent().getExtras());


        ivCard.setOnClickListener(v -> {
            Intent intent = new Intent(TrainDetailsActivity.this, StudentCardActivity.class);
            intent.putExtra("id", classId);
            startActivity(intent);
        });


        //notes();
        checkData();
        getTrainDetailsHead();


    }

    private void initTag() {

        fragmentList.add(offlineTrainFragment);
        mTitles.add("线下培训");

        if (notes) {
            fragmentList.add(handoutFragment);
            mTitles.add("电子讲义");
        }

        if (onlineTask) {
            trainTaskListFragment.classid = classId;
            fragmentList.add(trainTaskListFragment);
            mTitles.add("线上任务");
        }

        mViewPager2.setAdapter(new TrainListFragmentAdapter(this, fragmentList));
        if (fragmentList.size() > 1)
            mViewPager2.setOffscreenPageLimit(fragmentList.size() - 1);
        TabLayoutMediator mediator = new TabLayoutMediator(mTabLayout, mViewPager2,
                (tab, position) -> tab.setText(mTitles.get(position)));
        mediator.attach();
        //getTrainDetailsList();
    }

    private boolean notes = false;
    private boolean onlineTask = false;

    private void checkData() {
        showProgressDialog("");
        Observable<CommonResponse<NoteBean>> observable1 = RetrofitService.getNetService().notes(classId, 1, 1);
        Observable<CommonResponse<TrainAllBean>> observable2 = RetrofitService.getNetService().getTrainDetailsList(classId);
        addDisposable(Observable.zip(observable1, observable2, (noteBeanCommonResponse, trainAllBeanCommonResponse) -> {
            if (noteBeanCommonResponse.getStatusCode() == Constant.CODE_SUCCESS && trainAllBeanCommonResponse.getStatusCode() == Constant.CODE_SUCCESS) {
                return new Pair<>(noteBeanCommonResponse.getData(), trainAllBeanCommonResponse.getData());
            } else {
                return null;
            }
        }).observeOn(AndroidSchedulers.mainThread())
                .subscribe(noteBeanTrainAllBeanPair -> {
                    hideProgressDialog();
                    if (noteBeanTrainAllBeanPair != null) {
                        NoteBean noteBean = noteBeanTrainAllBeanPair.first;
                        if (noteBean.getRecords() != null && noteBean.getRecords().size() > 0) {
                            notes = true;
                        }
                        TrainAllBean trainAllBean = noteBeanTrainAllBeanPair.second;
                        if (trainAllBean.getTaskList() != null && trainAllBean.getTaskList().size() > 0) {
                            onlineTask = true;
                        }
                        initTag();
                    }
                }, throwable -> {
                    hideProgressDialog();
                    throwable.printStackTrace();
                }));
    }

    //培训头信息
    private void getTrainDetailsHead() {
        if (BaseApplication.getContext().getDataLogin() == null) {
            return;
        }
        addDisposable(RetrofitService.getNetService()
                .getTrainDetailsHead(classId, Constant.TRAIN_APP_KEY, BaseApplication.getContext().getDataLogin().getCurrentOrg(),
                        BaseApplication.getContext().getDataLogin().getUser().getId())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(response -> {
                    if (response.getStatusCode() == Constant.CODE_SUCCESS) {
                        if (offlineTrainFragment != null) {
                            offlineTrainFragment.trainDetailsBean = response.getData();
                        }
                        String clssname = response.getData().getClassName();
                        train_classname.setText(clssname);
                        String briefIntroduction = response.getData().getBriefIntroduction();
                        train_introduction.setText(briefIntroduction.equals("") ? "暂无简介" : briefIntroduction);
                        String startTime = response.getData().getStartTime();
                        String endTime = response.getData().getEndTime();
                        train_time.setText("有效期：" + splitTime(startTime) + " ～ " + splitTime(endTime)
                                + "\n总学时：" + response.getData().getClassHoursStr());
                        int way = response.getData().getWay();
                        if (way == 1) {
                            train_status.setText("线上");
                        } else if (way == 2) {
                            train_status.setText("面授");
                        } else if (way == 0) {
                            train_status.setVisibility(View.GONE);
                        }
                        showCertificateDialog(response.getData().getIsCertificate());
                    } else if (response.getStatusCode() != Constant.CODE_OFFLINE) {
                        showBindToast(response.getErrorInfo());
                    }
                }, Throwable::printStackTrace));

    }

    private void showCertificateDialog(int isCertificate) {
        if (isCertificate > 0) {
            new AlertDialog.Builder(getContext()).setTitle("提示")
                    .setMessage("恭喜您完成本次培训，获得培训证书！")
                    .setPositiveButton("去看看", (dialog, which) -> {
                        MyCertificateActivity.actionStart(getContext());
                        dialog.dismiss();
                    })
                    .setNegativeButton("关闭", null)
                    .create().show();
        }
    }

    public static String splitTime(String time) {
        String[] times = time.split(" ");
        return times[0];
    }

    @Override
    protected int getTitleStringRes() {
        return R.string.my_train_details;
    }


    public static class TrainListFragmentAdapter extends FragmentStateAdapter {

        private List<Fragment> mFragments;

        TrainListFragmentAdapter(@NonNull FragmentActivity fragmentActivity, List<Fragment> fragments) {
            super(fragmentActivity);
            mFragments = fragments;
        }

        @NonNull
        @Override
        public Fragment createFragment(int position) {
            return mFragments.get(position);
        }

        @Override
        public int getItemCount() {
            return mFragments.size();
        }
    }
}
